package com.zhixinsou.wuyang.process;

import com.alibaba.fastjson.JSON;
import com.zhixinsou.wuyang.model.AnalysisReport;
import com.zhixinsou.wuyang.model.SheetModel;
import com.zhixinsou.wuyang.util.FileUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ProcessPrudential {
    public static List<AnalysisReport> getAnalysisReportPageInfo(String filePath) {
        List<AnalysisReport> reports = new ArrayList<>();
        int startPage = 1;
        File file = new File(filePath);
        String[] lines = FileUtil.pdfReader(file, startPage, startPage).split("\r\n");
        Pattern pattern = Pattern.compile("([0-9]+)\\s-\\s([0-9]+)$");
        while (lines.length > 1 && lines[0].equals("Table of Contents")) {
            for (String line : lines) {
                Matcher matcher = pattern.matcher(line);
                if (matcher.find()) {
                    AnalysisReport report = new AnalysisReport();
                    report.setFilePath(filePath);
                    report.setFileName(file.getName());
                    report.setStartPage(Integer.parseInt(matcher.group(1)));
                    report.setEndPage(Integer.parseInt(matcher.group(2)));
                    report.setBrokerName("Prudential Financial");
                    
                    reports.add(report);
                }
            }

            startPage++;
            lines = FileUtil.pdfReader(filePath, startPage, startPage).split("\r\n");
        }
        return reports;
    }

    public static void getAnalysisReportDetail(AnalysisReport report) {
        Pattern patternVersion = Pattern.compile("Prudential_File\\s([0-9]+)[_]{0,1}");
        Matcher matcher = patternVersion.matcher(report.getFileName());
        if (matcher.find()) {
            int version = Integer.parseInt(matcher.group(1));
            if(version < 24)
                getAnalysisReportDetailVersion1_23(report);
            else {
                if(version == 24 && report.getStartPage() < 123)
                    getAnalysisReportDetailVersion1_23(report);
                else
                    getAnalysisReportDetailVersion24_33(report);
            }
        }
    }

    public static void getAnalysisReportDetailVersion1_23(AnalysisReport report) {
        String content = FileUtil.pdfReader(report.getFilePath(), report.getStartPage(), report.getStartPage());
        String[] lines = content.split("\r\n");

        //Date and CompanyName
        Pattern patternDate = Pattern.compile("(January|February|March|April|May|June|July|August|September|October|November|December){1}\\s*[0-9]+\\S\\s*[0-9]{4}");
        for (int i = 0; i < lines.length; i++) {
            String line = lines[i];
            Matcher matcherDate = patternDate.matcher(line);
            if (matcherDate.find()) {
                report.setDate(matcherDate.group());
                break;
            }
        }
        patternDate = Pattern.compile("(JANUARY|FEBRUARY|MARCH|APRIL|MAY|JUNE|JULY|AUGUST|SEPTEMBER|OCTOBER|NOVEMBER|DECEMBER){1}\\s*[0-9]+\\S\\s*[0-9]{4}");
        for (String line : lines) {
            Matcher matcherDate = patternDate.matcher(line);
            if (matcherDate.find()) {
                report.setDate(matcherDate.group());
                break;
            }
        }

        //Rating
        Pattern patternRating = Pattern.compile("(Rating:){1}\\s([a-zA-Z]+)\\s");
        for (String line : lines) {
            Matcher matcherRating = patternRating.matcher(line);
            if (matcherRating.find()) {
                report.setRating(matcherRating.group(2));
                break;
            }
        }

        //Prior recommendation
        String sentence = "";
        content = FileUtil.pdfReader(report.getFilePath(), report.getStartPage(), report.getStartPage(), false);
        lines = content.split("\r\n");
        for(int i = 0; i < lines.length; i++){
            String line = lines[i].trim();
            if(line.contains("Investment Opinion") || line.contains("Investment Overview")){
                sentence = line;
                i = i + 1;
                while(i < lines.length ){
                    sentence += lines[i];
                    if(lines[i].contains(".")){
                        break;
                    }else{
                        i++;
                    }
                }
                break;
            }
        }
        //选第一段话
        if(sentence.equals("")){
            content = FileUtil.pdfReader(report.getFilePath(), report.getStartPage(), report.getStartPage(),false);
            lines = content.split("\r\n");
            Pattern patternSentence = Pattern.compile("[A-Z][a-z]+\\s[a-z]+\\s[a-z]+\\s[a-z]+");
            for(int i = 0; i < lines.length; i++){
                String line = lines[i];
                Matcher matcherSentence = patternSentence.matcher(line);
                if(matcherSentence.find() && !line.startsWith("All important disclosures")){
                    sentence = line;
                    i = i + 1;
                    while(i < lines.length ){
                        sentence += lines[i];
                        if(lines[i].contains(".")){
                            break;
                        }else{
                            i++;
                        }
                    }
                    break;
                }
            }
        }
        report.setPriorRecommendation(sentence);

        content = FileUtil.pdfReader(report.getFilePath(), report.getStartPage(), report.getEndPage(),false);
        lines = content.split("\r\n");
        List<String> disclosures = new ArrayList<String>();
        List<String> temp = new ArrayList<String>();
        String disclosure = "";
        for(int i = 0; i < lines.length; i++){
            String line = lines[i].trim();
            if(line.contains("household has")) {
                int j = i + 1, k = i - 1;
                //往上和往下找整句
                while(!lines[k].contains(".") && k >= 0){
                    temp.add(lines[k]);
                    k--;
                }
                if(k >= 0)
                    temp.add(lines[k]);
                for(int m = temp.size() - 1; m >= 0; m--){
                    disclosure += temp.get(m) + " ";
                }
                temp.clear();
                disclosure += line + " ";
                while(!lines[j].contains(".") && j < lines.length){
                    disclosure += lines[j] + " ";
                    j++;
                }
                if(j < lines.length)
                    disclosure += lines[j] + " ";
            }
        }
        Pattern patternSentence = Pattern.compile(".*([A-Z][a-z\\S]+\\s[a-z\\S]+\\s[a-z\\S]+\\s[a-z\\S]+.*)");
        String[] values = disclosure.split("\\.");
        for(String value : values){
            System.out.println(value);
            Matcher matcherSentence = patternSentence.matcher(value);
            if(matcherSentence.find() && value.contains("household has")){
                disclosures.add(value);
                break;
            }
        }

        if(disclosures.size() == 0){
            for(String value : values){
                if(value.contains("household has")){
                    disclosures.add(value);
                    break;
                }
            }
        }

        report.setOwnershipDisclosures(disclosures);

        //Analyst name
        content = FileUtil.pdfReaderWithFontsAndColor(report.getFilePath(),report.getStartPage(),report.getStartPage());
        lines = content.split("\r\n");
        Pattern patternTel = Pattern.compile("(.*)(\\([0-9]+\\)\\s*[0-9]+\\-[0-9]+)");
        Pattern patternName = Pattern.compile("(Univers,BoldItalic\\]<9\\.0>)(.*)");
        for (int i = 0; i < lines.length; i++) {
            String line = lines[i];
            Matcher matcherTel = patternTel.matcher(line);
            if (matcherTel.find()) {
                for(int j = i - 1;j > 0; j--){
                    String value = lines[j];
                    Matcher matcherName = patternName.matcher(value);
                    if(matcherName.find()){
                        String originName = matcherName.group(2);
                        if(originName.contains("[")){
                            int end = originName.indexOf("[");
                            report.addAnalystName(originName.substring(0,end));
                        }
                        else
                            report.addAnalystName(originName);
                        break;
                    }
                }
            }
        }

        //Ticker
        Pattern patternTicker = Pattern.compile("BoldItalic\\]<12\\.0>([A-Z]+)\\s*(\\$[0-9]+).*");
        for (String line : lines) {
            Matcher matcherTicker = patternTicker.matcher(line);
            if (matcherTicker.find()) {
                report.setTicker(matcherTicker.group(1));
                break;
            }
        }

        if(report.getTicker().equals("")){
            patternTicker = Pattern.compile("([A-Z]+)\\s*(\\$[0-9]+\\.[0-9]+)\\s*[A-Za-z]+");
            for (String line : lines) {
                Matcher matcherTicker = patternTicker.matcher(line);
                if (matcherTicker.find()) {
                    System.out.println(String.format("The ticker line is %s", line));
                    report.setTicker(matcherTicker.group(1));
                }
            }
        }

        //Company Name
        Pattern patternCompany = Pattern.compile("Univers,BoldItalic\\]<24\\.0>(.*)");
        for (String line : lines) {
            Matcher matcherCompany = patternCompany.matcher(line);
            if (matcherCompany.find()) {
                String originCompany = matcherCompany.group(1);
                if(originCompany.contains("[")){
                    int end = originCompany.indexOf("[");
                    report.setCompanyName(originCompany.substring(0,end));
                }
                else{
                    report.setCompanyName(originCompany);
                }
                break;
            }
        }

        if(report.getAnalystNames() == null){
            //Company
            patternCompany = Pattern.compile("Arial,Bold\\]<12\\.0>(.*)");
            for (String line : lines) {
                Matcher matcherCompany = patternCompany.matcher(line);
                if (matcherCompany.find()) {
                    String originCompany = matcherCompany.group(1);
                    if(originCompany.contains("[")){
                        int end = originCompany.indexOf("[");
                        report.setCompanyName(originCompany.substring(0,end));
                    }
                    else{
                        report.setCompanyName(originCompany);
                    }
                    break;
                }
            }
            //Ticker
            patternTicker = Pattern.compile("([A-Z\\S]+)\\s\\|\\s(\\$[0-9]+.*)\\s\\|\\s([A-Za-z]+)");
            for(String line : lines){
                Matcher matcherTicker = patternTicker.matcher(line);
                if(matcherTicker.find()){
                    String originTicker = matcherTicker.group(1);
                    if(originTicker.contains(">")){
                        int end = originTicker.indexOf(">");
                        report.setTicker(originTicker.substring(end + 1));
                    }
                    else
                        report.setTicker(originTicker);
                    break;
                }
            }

            if(report.getTicker().equals("")){
                patternTicker = Pattern.compile("([A-Z]+)\\s*\\([A-Za-z]+\\)—\\s(\\$[0-9]+.*)");
                for (String line : lines) {
                    Matcher matcherTicker = patternTicker.matcher(line);
                    if (matcherTicker.find()) {
                        System.out.println(String.format("The ticker line is %s", line));
                        report.setTicker(matcherTicker.group(1));
                    }
                }
            }

            content = FileUtil.pdfReader(report.getFilePath(),report.getStartPage(),report.getStartPage());
            lines = content.split("\r\n");
            //Analyst name
            patternTel = Pattern.compile("(.*)•\\s[0-9]+.[0-9]+.[0-9]+.*@[a-zA-Z0-9-]+\\.");
            for(String line : lines){
                Matcher matcherTel = patternTel.matcher(line);
                if(matcherTel.find()){
                    report.addAnalystName(matcherTel.group(1));
                }
            }

            //Rating
            patternRating = Pattern.compile("Current:\\s(.*)");
            for(String line : lines){
                Matcher matcherRating = patternRating.matcher(line);
                if(matcherRating.find()){
                    report.setRating(matcherRating.group(1));
                    break;
                }
            }
        }

        report.setInitiatingCoverage("");
        report.setExchange("");
        System.out.println(JSON.toJSON(report));
    }

    public static void getAnalysisReportDetailVersion24_33(AnalysisReport report) {
        String content = FileUtil.pdfReader(report.getFilePath(), report.getStartPage(), report.getStartPage(),false);
        String[] lines = content.split("\r\n");

        //Date and CompanyName
        Pattern patternDate = Pattern.compile("(January|February|March|April|May|June|July|August|September|October|November|December){1}\\s*[0-9]+\\S\\s*[0-9]{4}");
        for (int i = 0; i < lines.length; i++) {
            String line = lines[i];
            Matcher matcherDate = patternDate.matcher(line);
            if (matcherDate.find()) {
                report.setDate(matcherDate.group());
                break;
            }
        }
        patternDate = Pattern.compile("(JANUARY|FEBRUARY|MARCH|APRIL|MAY|JUNE|JULY|AUGUST|SEPTEMBER|OCTOBER|NOVEMBER|DECEMBER){1}\\s*[0-9]+\\S\\s*[0-9]{4}");
        for (String line : lines) {
            Matcher matcherDate = patternDate.matcher(line);
            if (matcherDate.find()) {
                report.setDate(matcherDate.group());
                break;
            }
        }
        patternDate = Pattern.compile("(J anuary|F ebruary|M arch|Ap ril|M ay|Ju ne|Ju ly|Au gust|Se ptember|O ctober|N ovember|D ecember){1}\\s*[0-9]+\\S\\s*[0-9]{4}");
        for (int i = 0; i < lines.length; i++) {
            String line = lines[i];
            Matcher matcherDate = patternDate.matcher(line);
            if (matcherDate.find()) {
                report.setDate(matcherDate.group());
                break;
            }
        }

        content = FileUtil.pdfReader(report.getFilePath(), report.getStartPage(), report.getStartPage());
        lines = content.split("\r\n");
        //Rating
        Pattern patternRating = Pattern.compile("(Rating:){1}\\s([a-zA-Z]+)\\s");
        for (String line : lines) {
            Matcher matcherRating = patternRating.matcher(line);
            if (matcherRating.find()) {
                report.setRating(matcherRating.group(2));
                break;
            }
        }

        //Prior recommendation
        String sentence = "";
        content = FileUtil.pdfReader(report.getFilePath(), report.getStartPage(), report.getStartPage(), false);
        lines = content.split("\r\n");
        for(int i = 0; i < lines.length; i++){
            String line = lines[i].trim();
            if(line.contains("Investment Opinion") || line.contains("Investment Overview")){
                sentence = line;
                i = i + 1;
                while(i < lines.length ){
                    sentence += lines[i];
                    if(lines[i].contains(".")){
                        break;
                    }else{
                        i++;
                    }
                }
                break;
            }
        }
        //选第一段话
        if(sentence.equals("")){
            content = FileUtil.pdfReader(report.getFilePath(), report.getStartPage(), report.getStartPage(),false);
            lines = content.split("\r\n");
            Pattern patternSentence = Pattern.compile("[A-Z][a-z]+\\s[a-z]+\\s[a-z]+\\s[a-z]+");
            for(int i = 0; i < lines.length; i++){
                String line = lines[i];
                Matcher matcherSentence = patternSentence.matcher(line);
                if(matcherSentence.find() && !line.startsWith("All important disclosures")){
                    sentence = line;
                    i = i + 1;
                    while(i < lines.length ){
                        sentence += lines[i];
                        if(lines[i].contains(".")){
                            break;
                        }else{
                            i++;
                        }
                    }
                    break;
                }
            }
        }
        report.setPriorRecommendation(sentence);

        content = FileUtil.pdfReader(report.getFilePath(), report.getStartPage(), report.getEndPage(),false);
        lines = content.split("\r\n");
        List<String> disclosures = new ArrayList<String>();
        List<String> temp = new ArrayList<String>();
        String disclosure = "";
        for(int i = 0; i < lines.length; i++){
            String line = lines[i].trim();
            if(line.contains("household has")) {
                int j = i + 1, k = i - 1;
                //往上和往下找整句
                while(!lines[k].contains(".") && k >= 0){
                    temp.add(lines[k]);
                    k--;
                }
                if(k >= 0)
                    temp.add(lines[k]);
                for(int m = temp.size() - 1; m >= 0; m--){
                    disclosure += temp.get(m) + " ";
                }
                temp.clear();
                disclosure += line + " ";
                while(!lines[j].contains(".") && j < lines.length){
                    disclosure += lines[j] + " ";
                    j++;
                }
                if(j < lines.length)
                    disclosure += lines[j] + " ";
            }
        }
        Pattern patternSentence = Pattern.compile(".*([A-Z][a-z\\S]+\\s[a-z\\S]+\\s[a-z\\S]+\\s[a-z\\S]+.*)");
        String[] values = disclosure.split("\\.");
        for(String value : values){
            System.out.println(value);
            Matcher matcherSentence = patternSentence.matcher(value);
            if(matcherSentence.find() && value.contains("household has")){
                disclosures.add(value);
                break;
            }
        }

        if(disclosures.size() == 0){
            for(String value : values){
                if(value.contains("household has")){
                    disclosures.add(value);
                    break;
                }
            }
        }

        report.setOwnershipDisclosures(disclosures);

        content = FileUtil.pdfReader(report.getFilePath(),report.getStartPage(),report.getStartPage(),false);
        lines = content.split("\r\n");
        if(report.getAnalystNames() == null){
            //Company
            report.setCompanyName(lines[0].trim());
            //Ticker
            Pattern patternTicker = Pattern.compile("([A-Z\\S]+)\\s\\|\\s(\\$[0-9]+.*)\\s\\|\\s([A-Za-z]+)");
            for(String line : lines){
                Matcher matcherTicker = patternTicker.matcher(line);
                if(matcherTicker.find()){
                    String originTicker = matcherTicker.group(1);
                    if(originTicker.contains(">")){
                        int end = originTicker.indexOf(">");
                        report.setTicker(originTicker.substring(end + 1));
                    }
                    else
                        report.setTicker(originTicker);
                    break;
                }
            }

            if(report.getTicker().equals("")){
                patternTicker = Pattern.compile("([A-Z]+)\\s*\\([A-Za-z]+\\)—\\s(\\$[0-9]+.*)");
                for (String line : lines) {
                    Matcher matcherTicker = patternTicker.matcher(line);
                    if (matcherTicker.find()) {
                        System.out.println(String.format("The ticker line here is %s", line));
                        report.setTicker(matcherTicker.group(1));
                    }
                }
            }

            //Analyst name
            Pattern patternTel = Pattern.compile("(.*)•\\s[0-9]+.[0-9]+.[0-9]+.*@[a-zA-Z0-9-]+\\.");
            for(String line : lines){
                Matcher matcherTel = patternTel.matcher(line);
                if(matcherTel.find()){
                    report.addAnalystName(matcherTel.group(1));
                }
            }

            //Rating
            patternRating = Pattern.compile("Current:\\s(.*)");
            for(String line : lines){
                Matcher matcherRating = patternRating.matcher(line);
                if(matcherRating.find()){
                    report.setRating(matcherRating.group(1));
                    break;
                }
            }

            if(report.getRating().equals("")){
                content = FileUtil.pdfReader(report.getFilePath(),report.getStartPage(),report.getStartPage());
                lines = content.split("\r\n");
                patternRating = Pattern.compile("(Rating:){1}\\s*(.*)");
                for (String line : lines) {
                    Matcher matcherRating = patternRating.matcher(line);
                    if (matcherRating.find()) {
                        report.setRating(matcherRating.group(2));
                    }
                }
            }
        }

        report.setInitiatingCoverage("");
        report.setExchange("");
        System.out.println(JSON.toJSON(report));
    }

    public static void process(String rootDir, String resultPath) {
        List<AnalysisReport> reports = new ArrayList<>();
        File[] Files = new File(rootDir).listFiles();
        for (File file : Files) {
            if(file.getName().endsWith(".pdf"))
                reports.addAll(getAnalysisReportPageInfo(file.getPath()));
        }

        //以下代码为写入excel
        List<String> headers = new ArrayList<>();
        headers.add("Date");
        headers.add("Broker name");
        headers.add("Analyst name");
        headers.add("Company name");
        headers.add("Ticker");
        headers.add("Exchange");
        headers.add("Rating");
        headers.add("Initiating Coverage");
        headers.add("Prior recommendation");
        headers.add("Ownership disclosure");
        headers.add("PDF file name");
        headers.add("StartPage");
        headers.add("EndPage");
        SheetModel sheetModel = FileUtil.makeSheet(resultPath, "result", headers);

        List<String[]> data = new ArrayList<>();
        for (AnalysisReport report : reports) {
            try {
                getAnalysisReportDetail(report);
            } catch (Exception e) {
                System.out.println(JSON.toJSON(report));
                e.printStackTrace();
                continue;
            }

            String[] line = new String[]{report.getDate(),
                    report.getBrokerName(),
                    JSON.toJSONString(report.getAnalystNames()),
                    report.getCompanyName(),
                    report.getTicker(),
                    report.getExchange(),
                    report.getRating(),
                    report.getInitiatingCoverage(),
                    report.getPriorRecommendation(),
                    JSON.toJSONString(report.getOwnershipDisclosures()),
                    report.getFileName(),
                    report.getStartPage() + "",
                    report.getEndPage() + ""};
            data.add(line);
        }

        FileUtil.exportSheet(sheetModel.getSheet(), data);
        FileUtil.closeSheet(sheetModel);
        System.out.println("Success!");
    }
}
